package org.looop.studio.noots.extension;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.WhitespaceAnalyzer;
import org.apache.lucene.queryParser.ParseException;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.store.Directory;
import org.looop.studio.noots.BaseTestCase;

public class QueryParserTest extends BaseTestCase {
	
	private Analyzer analyzer;
	private Directory directory;
	
	@Override
	protected void setUp() throws Exception {
		analyzer = getAnalyzer();
		String[] idArray = new String[500];
		for (int i = 0; i < idArray.length; i++) {
			idArray[i] = NumberUtils.pad(i + 1);
		}
		directory = createSingleFieldIndex("id", idArray, analyzer);
	}
	
	public void testCustomQueryParser(){
		CustomQueryParser parser = new CustomQueryParser("field", getAnalyzer());
		try{
			parser.parse("a?t");
			fail("Wildcard queries should not be allowed");
		}catch(ParseException e){
			assertTrue(true);
		}
		
		try{
			parser.parse("xunit~");
			fail("Fuzzy queries should not be allowed");
		}catch(ParseException e){
			assertTrue(true);
		}
	}
	
	public void testIdRangeQuery() throws Exception {
		CustomQueryParser parser = new CustomQueryParser("field", getAnalyzer());
		Query query = parser.parse("id:[37 TO 346]");
		assertEquals("id:[0000000037 TO 0000000346]", query.toString());
		
		IndexSearcher searcher = new IndexSearcher(directory);
		Hits hits = searcher.search(query);
		
		assertEquals(310, hits.length());
	}
	
	@Override
	protected Analyzer getAnalyzer() {
		return new WhitespaceAnalyzer();
	}
}
